package com.syzg.view.tags;

import java.io.IOException;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import com.syzg.base.merge.model.TaskTreeNode;
import com.syzg.core.util.StringUtil;

public class TreeTag extends SimpleTagSupport {
	
	private String id;
    private String value;
    private String methodName;
    private String parentNodeClass;
    private String headClass;
    private String tailClass;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public String getHeadClass() {
		return headClass;
	}

	public void setHeadClass(String headClass) {
		this.headClass = headClass;
	}

	public String getTailClass() {
		return tailClass;
	}

	public void setTailClass(String tailClass) {
		this.tailClass = tailClass;
	}

	public String getParentNodeClass() {
		return parentNodeClass;
	}

	public void setParentNodeClass(String parentNodeClass) {
		this.parentNodeClass = parentNodeClass;
	}

	@Override
	public void doTag() throws JspException, IOException {
		JspWriter out = this.getJspContext().getOut();
		PageContext pageContext = (PageContext)getJspContext();
		if(StringUtil.isEmpty(value)){
			return;
		}
		TaskTreeNode root = (TaskTreeNode)pageContext.getRequest().getAttribute(value);
		StringBuffer sb = new StringBuffer("<li class=\"treeview\">");
		for(TaskTreeNode taskTreeNode : root.getSubNodes()){
			sb.append(getTreeStr(taskTreeNode));
		}
		sb.append("</li>");
		out.println(sb.toString());
	}
	
	public String getTreeStr(TaskTreeNode taskTreeNode){
		StringBuffer sb = new StringBuffer();
		if(taskTreeNode.isLeaf()){
			sb.append("<li><a href=\"javascript:;\" onclick=\"");
			sb.append(methodName);
			sb.append("('");
			sb.append(taskTreeNode.getUrl());
			sb.append("');\">&nbsp;&nbsp;<i class=\"");
			sb.append(taskTreeNode.getIconStyle()==null ? "fa fa-file-o" : taskTreeNode.getIconStyle());
			sb.append("\"></i>");
			sb.append(taskTreeNode.getText());
			sb.append("</a></li>");
		} else {
			sb.append("<li>");
			sb.append("<a href=\"#\"><i class=\"");
			sb.append(taskTreeNode.getIconStyle()==null ? "fa fa-folder-o" : taskTreeNode.getIconStyle());
			sb.append("\"></i>");
			sb.append(taskTreeNode.getText());
			sb.append("<i class=\"");
			sb.append(tailClass);
			sb.append("\"></i></a>");
			sb.append("<ul class=\"");
			sb.append(parentNodeClass);
			sb.append("\">");
			for(TaskTreeNode subNode : taskTreeNode.getSubNodes()){
				sb.append(getTreeStr(subNode));
			}
			sb.append("</ul>");
			sb.append("</li>");
		}
		return sb.toString();
	}
}
